package com.cfswt.tasksystem.security;

import com.cfswt.tasksystem.mapper.UserMapper;
import com.cfswt.tasksystem.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 该类定义SpringSecurity的封装细节
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO userVO = userMapper.selectUserByName(username);
        if (userVO == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        List<String> authorities = new ArrayList<>();
        authorities.add("ROLE_ACTIVITI_USER");
        if (userVO.getIsAdmin() == 1) {
            authorities.add("ROLE_SHOW_PRICE");
            authorities.add("ROLE_SHOW_WMS");
            if (username.equals("tangyan") || username.equals("zhaohongyu")
                    || username.equals("mengqiang") || username.equals("chaisanpeng")
                    || username.equals("liyingdi")) {
                authorities.remove("ROLE_SHOW_PRICE"); // 确保不包含查看价格权限
            } else if (username.equals("cfswt")) {
                authorities.add("ROLE_SHOW_PROCESSMENU");
            }
        }

        CustomUserDetails userDetails = new CustomUserDetails(
                userVO.getId(),
                userVO.getNickName(),
                userVO.getIsAdmin(),
                userVO.getAvatar(),
                userVO.getEmail(),
                userVO.getMobile(),
                userVO.getDepId(),
                userVO.getRoles(),
                username,
                userVO.getPassword(),
                AuthorityUtils.createAuthorityList(authorities.toArray(new String[0])));
        return userDetails;
    }
}
